package com.sc.sso.service.impl;

import com.sc.common.pojo.CommonResult;
import com.sc.common.utils.CookieUtils;
import com.sc.common.utils.JsonUtils;
import com.sc.mapper.TbUserMapper;
import com.sc.pojo.TbUser;
import com.sc.pojo.TbUserExample;
import com.sc.sso.dao.JedisClient;
import com.sc.sso.service.SsoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * @auther sc
 * @Date 2017/11/5
 */
@Service
public class SsoServiceImpl implements SsoService {

    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value(("${REDIS_SESSION_KEY}"))
    private String REDIS_SESSION_KEY;
    @Value(("${REDIS_SESSION_EXPIRE}"))
    private int REDIS_SESSION_EXPIRE;

    @Override
    public CommonResult  checkData(String param, Integer type) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        //1,2,3 username. phone. email
        if(1==type){
            criteria.andUsernameEqualTo(param);
        }else if(2==type){
            criteria.andPhoneEqualTo(param);
        }else if(3==type){
            criteria.andEmailEqualTo(param);
        }
        List<TbUser> users = tbUserMapper.selectByExample(example);
        if(users==null||users.isEmpty()){
            return CommonResult.ok(true);
        }
        return CommonResult.ok(false );
    }

    @Override
    public CommonResult register(TbUser user) {
        if(StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())){
            return CommonResult.build(400,"用户名或密码不能为空");
        }
        //校验用户名
        CommonResult result = checkData(user.getUsername(), 1);
        if(!(boolean)result.getData()){
            return CommonResult.build(400,"用户名重复");
        }
        if(user.getPhone()!=null) {
            CommonResult result1 = checkData(user.getPhone(), 2);
            if(!(boolean)result1.getData()){
                return CommonResult.build(400,"手机号码不可用");
            }
        }
        if(user.getEmail()!=null){
            CommonResult result2 = checkData(user.getEmail(), 3);
            if(!(boolean)result2.getData()){
                return CommonResult.build(400,"邮箱不可用");
            }
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        tbUserMapper.insert(user);
        return CommonResult.ok();
    }

    @Override
    public CommonResult login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //校验用户名和密码
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> list = tbUserMapper.selectByExample(example);
        if(list==null||list.isEmpty()){
            return CommonResult.build(400,"用户名或密码错误");
        }
        TbUser user = list.get(0);
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            return CommonResult.build(400,"用户名或密码错误");
        }
        //生成token
        String token = UUID.randomUUID().toString();
        //写入redis
        //key:
        user.setPassword(null);
        try {
            jedisClient.set(REDIS_SESSION_KEY+":"+token, JsonUtils.objectToJson(user));
            jedisClient.expire(REDIS_SESSION_KEY+":"+token,REDIS_SESSION_EXPIRE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //写cookie
        CookieUtils.setCookie(request,response,"user_token",token,REDIS_SESSION_EXPIRE);
        return CommonResult.ok(token);
    }

    @Override
    public CommonResult getUserByToken(String token) {
        String json = jedisClient.get(REDIS_SESSION_KEY+":"+token);
        if(StringUtils.isBlank(json)){
            return CommonResult.build(400,"登录过期");
        }
        TbUser user = JsonUtils.jsonToPojo(json,TbUser.class);
        //更新token过期时间
        jedisClient.expire(REDIS_SESSION_KEY+":"+token,REDIS_SESSION_EXPIRE);
        return CommonResult.ok(user);
    }

    @Override
    public CommonResult logout(String token,HttpServletRequest request,HttpServletResponse response) {
        jedisClient.del(REDIS_SESSION_KEY+":"+token);
        CookieUtils.deleteCookie(request,response,"user_token");
        return CommonResult.ok();
    }
}
